
from  rest_framework import  serializers

from smart.models import Banner, Notice, Collection, Area
from libs.baidu_ai import BaiduFace
from rest_framework.exceptions import APIException

class BannerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Banner
        fields = '__all__'


class NoticeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Notice
        fields = '__all__'


class CollectionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Collection
        fields = ['id','name','avatar','area']
        depth = 1 # 外键关联区域对象

class CollectionSaveSerializer(serializers.ModelSerializer):
    class Meta:
        model = Collection
        fields =  ['name','avatar','area']

    def create(self, validated_data):
        # 1 上传到百度人脸识别
        ai = BaiduFace()
        # 2 取出图片
        upImg = validated_data.get("avatar")
        name = validated_data.get("name")
        # 3 把人名转为拼音
        name_pinyin = ai.name_pinyin(name)
        # 4 添加用户到百度人脸识别
        res = ai.add_user(upImg, name_pinyin)
        # 5 上传成功，把faceToken 存到自己表中
        if res.get("error_code") == 0:
            # 返回来的值再赋值给数据对象，方便保存到数据表
            validated_data["face_token"] = res.get('result').get('face_token')
            validated_data["name_pinyin"] = name_pinyin
            print(validated_data)
            # 6 真正保存到数据库
            instance = super().create(validated_data)
            return  instance
        else:
            raise APIException('创建人脸识别失败！')


class AreaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Area
        fields = ['id','name','desc']


## 统计列表数据
class StatisticsListSerializer(serializers.Serializer):
    date = serializers.DateTimeField(format='%Y年%m月%d日')
    count = serializers.IntegerField()

